package net.doglog;

import javax.jdo.annotations.*;

import com.google.appengine.api.datastore.Blob;

/**
 * Forget about java.io.File and use this. Google App Engine 
 * doesn't allow writing to file system, so we have to save 
 * all our uploaded files in the database.
 * 
 * @author oipn4e2
 *
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class File {
	/**
	 * This is the same hack used in class Post.
	 * @see net.doglog.Post#prefix
	 */
	@NotPersistent
	public static final String prefix = "file";

	@NotPersistent
	public static final long maxAge = 1L * 60 * 60 * 24 * 365;
	
	@NotPersistent
	public static final long expire = 1000L * maxAge;
	
	/**
	 * Files are identified with file names. :)
	 */
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private String name;
	
	public void setName(String name) {
		this.name = prefix + name;
	}
	
	public String getName() {
		return name.substring(prefix.length());
	}
	
	/**
	 * Content type is fetched automatically using MultipartParser.
	 */
	@Persistent
	private String contentType;
	
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	
	public String getContentType() {
		return contentType;
	}
	
	/**
	 * Timestamp of last modification. Updated automatically.
	 * @see setContent
	 */
	@Persistent
	private long lastModified;
	
	public long getLastModified() {
		return lastModified;
	}
	
	/**
	 * File content stored in a Blob. GAE doesn't support arrays.
	 */
	@Persistent(defaultFetchGroup = "true")
	private Blob content;
	
	public void setContent(byte[] content) {
		this.content = new Blob(content);
		this.lastModified = System.currentTimeMillis();
	}
	
	public byte[] getContent() {
		return content.getBytes();
	}

	/**
	 * Save a file using transaction.
	 * @see net.doglog.FileUtil#saveFile(File)
	 * @return operation result (true if succeed)
	 */
	public boolean save() {
		return FileUtil.saveFile(this);
	}
	
}
